//document.write('<script type="text/javascript" src="http://pic.ku.duowan.com/js/jcookie.js"><\/script>');
var DWCmsVote = {};
DWCmsVote.sUrl = "http://comment3.duowan.com/";		//通用投票站点
DWCmsVote.getVoteDataUrl = "?r=vote/GetVote";
DWCmsVote.postVoteDataUrl = "?r=vote/op"
DWCmsVote.vDomain = window.location.host;			//加载投票的站点
DWCmsVote.voteUrl = window.location.pathname;	//
DWCmsVote.cmsVoteUniqid = typeof(cmsVoteUniqid) == 'undefined' || cmsVoteUniqid == '' ?  0  : cmsVoteUniqid;  //页面key，投票由此key去拉对应的投票信息
DWCmsVote.frameId = "#cmsVote_frame";	//投票最外层div
DWCmsVote.htmlData = DWCmsVote.jsonData = '';
DWCmsVote.cmsVote_inited = 0;  //投票初始化加载标记
DWCmsVote.divData = [];
DWCmsVote.voteData = [];//投票数据
DWCmsVote.postData = [];//用于投票提交数据 topicId-opt_id,opt_id | topicId_opt_id,
//DWCmsVote.skin = typeof(skin) == 'undefined' || skin == '' ? 'dw-comment-skin_yellow' : 'dw-comment-'+skin;  //评论样式
DWCmsVote.cmsVote_scroll = '';
DWCmsVote.loaded = false;		//投票已完成加载标记

DWCmsVote.cookieUtil = {
			getCookie : function (cookieName) {
				var cookies=decodeURI(document.cookie).split(";");//一个分号加一个空格
				if (!cookies.length) {return "";}
				for (var i=0;i< cookies.length;i++) {
					var pair = cookies[i].split("=");//以赋值号分隔,第一位是Cookie名,第二位是Cookie值
					if (pair[0] && pair[0].replace(/(^\s*)|(\s*$)/g,'')==cookieName) {
						return pair[1];
					}
				}
				return '';
			},
			setCookie : function (name,value,time) {
				var expiresDate  = new Date();   
				expiresDate.setTime(expiresDate.getTime() + parseInt(time)*1000);//30天过期时间
				var str = name+"="+encodeURI(value)  + "; expires="+expiresDate.toGMTString();
				document.cookie = str;
			}
	};
DWCmsVote.changeTimeFormat = function (time) {
    var date = new Date(time);
    var month = date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1;
    var currentDate = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
    var hh = date.getHours() < 10 ? "0" + date.getHours() : date.getHours();
    var mm = date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes();
    return date.getFullYear() + "-" + month + "-" + currentDate+" "+hh + ":" + mm;
    //返回格式：yyyy-MM-dd hh:mm
}

/*
*加载最开始的投票资料
*/
DWCmsVote.loadData = function(){
	jQuery(this.frameId).html('<center><img src="http://comment3.duowan.com/img/loading.gif"></center>');
	this.htmlData = '';
	jQuery.ajax({
		type: "post",
		url: this.sUrl + this.getVoteDataUrl,
		data: {"vote" : this.cmsVoteUniqid},
		dataType: "jsonp",
		jsonp: "callback",
		jsonpCallback: "AllVoteData",
		success:function(d){
			DWCmsVote.loaded = true;
			DWCmsVote.jsonData = d;
			if(jQuery.isEmptyObject(DWCmsVote.jsonData)){
				alert("投票不存在!");
			}else{
				DWCmsVote.render();
			}
		},
		error:function(){
			jQuery(DWCmsVote.frameId).html('');
		}
	});
}

DWCmsVote.render = function(){
	//判断cookie是否已经投过票
	var voteDataStr = DWCmsVote.cookieUtil.getCookie('voteId_' + DWCmsVote.jsonData['voteId']);
	
	//是否已经开始
	var isStart = true;
	//是否已经结束
	var isEnd = false;
	
	var startTime = DWCmsVote.jsonData['startTime'];
	var endTime = DWCmsVote.jsonData['endTime'];
	
	var now = new Date().getTime();
	if(parseInt(startTime * 1000) > now){
		isStart = false;
	}
	if(parseInt(endTime * 1000) < now){
		isEnd = true;
	}
	//存在cookie或者不隐藏结果则显示结果
	if(voteDataStr){
		DWCmsVote.renderVote(true, false, isStart, isEnd, true);
	}else if(!isStart){
		DWCmsVote.renderVote(false, false, isStart, isEnd, false);
	}else if(isEnd){
		DWCmsVote.renderVote(true, false, isStart, isEnd, false);
	}else if(DWCmsVote.jsonData['hide_result'] != 1){
		DWCmsVote.renderVote(true, true, isStart, isEnd, false);
	}else{
		DWCmsVote.renderVote(false, true, isStart, isEnd, false);
	}
	
}

//渲染投票页showResult:是否显示结果;voteable：是否可投票
DWCmsVote.renderVote = function(showResult, voteable, isStart, isEnd, isAfterVote){
	
	var templateOpt = DWCmsVote.jsonData['template'];
	var vote_ctn = '<div class="dw-vote-ctn">';
	if(templateOpt == "2"){//深色
		vote_ctn = '<div class="dw-vote-ctn dw-vote-ctn-s3">';
	}
	
	var voteId = DWCmsVote.jsonData['voteId'];
	//是否显示描述
	var description = '';
	if(DWCmsVote.jsonData['description'] == ''){
		description = '';
	}else if(DWCmsVote.jsonData['hide_description'] != 1 || isEnd || isAfterVote){
		description = '<div class="dw-vote-hidebox">' + 
							'<p>'+DWCmsVote.jsonData['description']+'</p>' + 
						'</div>';
	}else{
		description = '<div class="dw-vote-hidebox">' + 
							'<span class="hide-note">隐藏内容投票后可见</span>' + 
						'</div>';
	}
	
	
	var start = DWCmsVote.changeTimeFormat(DWCmsVote.jsonData['startTime'] * 1000);
	var end = DWCmsVote.changeTimeFormat(DWCmsVote.jsonData['endTime'] * 1000);
	
	var htmlData = vote_ctn + 
					'<div class="dw-vote-hd">' + 
					'<h2>'+DWCmsVote.jsonData['title']+'<span class="note-desc"></span></h2>' +
					'<div class="info">' + 
						'<span class="vote-people">'+DWCmsVote.jsonData['all_number']+'人投票</span>' + 
						'<span class="vote-time">投票时间：<em>'+start+'</em>至<em>'+end+'</em></span>' + 
					'</div>' + description + 
					'<div class="dw-vote-bd">' + 
						'<form id="vote" action="" method="post" >';
						
	var topics = DWCmsVote.jsonData['topics'];				
	for(topic_index in topics){
		var topicId = topics[topic_index]['topicId'];//主题id
		var topic = topics[topic_index]['topic'];//主题
		var voteType = topics[topic_index]['voteType'];//投票类型 单选/多选
		var ext = '';
		if(voteType > 1){
			ext = '(最多可选'+voteType+'项)';
		}
		
		//若要显示结果，计算总数
		var total_votes = 0;
		if(showResult){
			var data = topics[topic_index]['data'];
			for(data_index in data){
				total_votes = total_votes + parseInt(data[data_index]['opt_vote']);
				if(DWCmsVote.voteData.length > 0){
					total_votes = total_votes + parseInt(DWCmsVote.voteData[topic_index][data_index]);
				}
			}
		}
		
		htmlData += '<div class="dw-vote-content" key="topicId_'+topicId+'">' + 
						'<div class="dw-vote-item-hd"><h3>' + topic + '<span class="note-desc">' + ext + '</span></h3></div>' + 
						'<div class="dw-vote-item-bd">' + 
							'<ul class="dw-vote-list">';
		var data = topics[topic_index]['data'];
		var tmp_i = 0;
		for(data_index in data){
			
			var opt_id = data[data_index]['opt_id'];
			var postId = topicId + "_" + opt_id;
			var opt_des = data[data_index]['opt_des'];
			//若要显示结果，计算投票项
			var vote_bar = '';//进度条
			var opt_voteStr = '';
			if(showResult){
				var opt_vote = parseInt(data[data_index]['opt_vote']);
				if(DWCmsVote.voteData.length > 0){
					opt_vote = opt_vote +  parseInt(DWCmsVote.voteData[topic_index][data_index]);
				}
				if(total_votes == 0)total_votes = 1;
				var percent = (parseInt(opt_vote)/parseInt(total_votes))*100;
				
				vote_bar = '<div class="vote-bar"><span class="vote-bar-inner"></span></div>';
				opt_voteStr = '<div class="vote-state">' + 
								'<span class="persent">'+percent.toFixed(2)+'%</span>' + 
								'<span class="vote-num">('+opt_vote+')</span>' + 
							'</div>';
			}
			var color = (tmp_i++) % 5;
			htmlData += '<li class="vote-list-c'+(color + 1)+'">';
			//如果可投票
			if(voteable){
				if(voteType > 1){
					htmlData += '<input class="vote-input" type="checkbox" value="'+opt_id+'" name="opt_in_'+topicId+'" id="'+postId+'" maxNum="'+voteType+'"/>';
				}else{
					htmlData += '<input class="vote-input" type="radio" value="'+opt_id+'" name="opt_in_'+topicId+'" id="'+postId+'"/>';
				}
			}else {
				postId = '';
			}
			
			htmlData += '<div class="vote-handle">' + 
							'<label for="'+postId+'">'+opt_des+'</label>' + vote_bar + 
						'</div>' + opt_voteStr +
						'</li>';
		}
		htmlData += '</ul></div></div>';
	}
	var voteButtonStr = '<span class="dw-vote-button"><input class="handle" type="submit" value="投票" /></span>';
	var voted_tip = '';
	if(!voteable){
		voteButtonStr = '';
		voted_tip = '<span class="vote-tips">您已经投过票，谢谢您的参与！</span>'
	}
	if(!isStart){
		voteButtonStr = '';
		voted_tip = '<span class="vote-tips">该投票还未开始。</span>';
	}
	if(isEnd){
		voteButtonStr = '';
		voted_tip = '<span class="vote-tips">该投票已经结束。</span>';
	}
	htmlData += '<div class="dw-vote-ft">' + 
					 voteButtonStr + voted_tip +
				'</div>' + 
				'</form></div>';
	if(showResult){
		jQuery(DWCmsVote.frameId).html(htmlData).fadeIn("slow",function(){
    		DWCmsVote.animateResults();});
	}else{
		jQuery(this.frameId).html(htmlData);
	}
	//表单校验
	jQuery("#vote").submit(DWCmsVote.validateAndPost);
	//checkbox校验
	jQuery(":checkbox").click(function(){
		var selector_name = $(this).attr('name');
		var maxNum = parseInt($(this).attr('maxNum'));
		var checkedNum = $(':checkbox[name="'+selector_name+'"]:checked').length;
		if(checkedNum == maxNum){
			$(':checkbox[name="'+selector_name+'"]').not(':checked').attr('disabled', 'disabled');
		}else{
			$(':checkbox[name="'+selector_name+'"]').removeAttr('disabled');
		}
	})
	
}

DWCmsVote.validateAndPost = function(event){
	event.preventDefault();
	//清除样式
	jQuery('div[key^="topicId_"]').removeClass("dw-vote-content-requier");
	//校验数据
	var topics = DWCmsVote.jsonData['topics'];				
	for(topic_index in topics){
		var topicId = topics[topic_index]['topicId'];//主题id
		var voteType = topics[topic_index]['voteType'];//投票类型 单选/多选
		
		var data = topics[topic_index]['data'];
		var choose = 0;
		var tmp_inc = 0;
		DWCmsVote.voteData[topic_index] = [];
		DWCmsVote.postData[topic_index] = topicId + "_";
		jQuery(":input[name='opt_in_"+topicId+"']").each(function(){
					if(this.checked){
						DWCmsVote.voteData[topic_index][tmp_inc ++] = 1;
						choose ++;
						DWCmsVote.postData[topic_index] +=  jQuery(this).val() + ","
					}else{
						DWCmsVote.voteData[topic_index][tmp_inc ++] = 0;
					}
				})
		if(choose <=0 || choose > voteType){
			
			var topic_txt = topics[topic_index]['topic'];
			if(topic_txt.length > 15){
				topic_txt = topic_txt.substring(0, 15) + "...";
			}
			if(choose == 0){
				alert("主题：" + topic_txt + " 没有选择");
			}else{
				alert("主题：" + topic_txt + " 不能超过" + voteType + "个");
			}
			jQuery('div[key="topicId_'+topicId+'"]').addClass("dw-vote-content-requier");
			DWCmsVote.voteData = [];
			DWCmsVote.postData = [];
			return;
		}
	}
	//总人数加1
	DWCmsVote.jsonData['all_number'] = parseInt(DWCmsVote.jsonData['all_number']) + 1;
	
	//加cookie
	var data_cookie = "";
	for(data_index in DWCmsVote.voteData){
		for(sec_index in DWCmsVote.voteData[data_index])
			data_cookie +=  DWCmsVote.voteData[data_index][sec_index] + ",";
		data_cookie += "|";	
	}
	var cookieTime = parseInt(DWCmsVote.jsonData['limitMode']);
	DWCmsVote.cookieUtil.setCookie('voteId_' + DWCmsVote.jsonData['voteId'],data_cookie,cookieTime);
	
	//显示结果:1.先加DWCmsVote.jsonData
	DWCmsVote.renderVote(true, false, true, false, true);
	
	
	
	//组织数据进行投票 alert(DWCmsVote.postData);
	DWCmsVote.postVote();
	
}

DWCmsVote.postVote = function(){
	
	var optionStr = "";
	
	if(DWCmsVote.postData.length > 0){
		for(postData_index in DWCmsVote.postData){
			optionStr += DWCmsVote.postData[postData_index] + "|";
		}	
		//alert(optionStr);
	}
	
	//jQuery.get(DWCmsVote.sUrl + DWCmsVote.postVoteDataUrl + DWCmsVote.cmsVoteUniqid + optionStr);
	
	jQuery.ajax({
		type: "post",
		url: DWCmsVote.sUrl + DWCmsVote.postVoteDataUrl,
		data: {"vote":DWCmsVote.cmsVoteUniqid, "op":optionStr},
		dataType: "jsonp",
		jsonp: "callback",
		jsonpCallback: "postData",
		success:function(d){
		},
		error:function(){
			alert('提交错误');
		}
	});
	
}

/*
 * 动态效果
 */
DWCmsVote.animateResults = function() {
	jQuery("div .vote-bar-inner").each(function(){
      var percentage = jQuery(this).parent().parent().siblings(".vote-state").find(".persent").text();
      var tmp = percentage.substring(0, percentage.length - 1);
      if(Number(tmp) < 0.0001){
    	  percentage = "0.2%";
      }
      jQuery(this).css({width: "0%"}).animate({
				width: percentage}, 'slow');
      
  });
}

/*
*	投票加载判断 
*/
DWCmsVote.cmsVoteOnload = function(){
	
	var c = document.documentElement.clientHeight || document.body.clientHeight;
	var t = jQuery(document).scrollTop();
	if( t + c >= jQuery(this.frameId).offset().top + jQuery(this.frameId).height() - 150){
		this.loadData();
		this.cmsVote_inited = 1;
	}
	else{
		this.cmsVote_scroll = jQuery('.cmsVote_scroll_element').length > 0 ? '.cmsVote_scroll_element' : window;
		jQuery(this.cmsVote_scroll).bind("scroll", this.scrollHandler);
	}
}

/*
*	下拉时加载
*/
DWCmsVote.sTimer;
DWCmsVote.scrollHandler = function() {
			clearTimeout(DWCmsVote.sTimer);
			DWCmsVote.sTimer = setTimeout(function() {
				if (DWCmsVote.cmsVote_inited == 1) {
					jQuery(DWCmsVote.cmsVote_scroll).unbind("scroll", DWCmsVote.scrollHandler);
				} else {
					var c = document.documentElement.clientHeight
							|| document.body.clientHeight, t = jQuery(document)
							.scrollTop();
					if (t + c >= jQuery(DWCmsVote.frameId).offset().top
							+ jQuery(DWCmsVote.frameId).height() - 350) {
						DWCmsVote.loadData();
						DWCmsVote.cmsVote_inited = 1;
					}
				}
			}, 100)};
			
DWCmsVote.loadCss = function(){
	var style = document.createElement("link");
	style.rel = "stylesheet";
	style.href = DWCmsVote.sUrl + 'img/vote/css/main.css';
	document.getElementsByTagName("head")[0].appendChild(style);
	
	var style2 = document.createElement("link");
	style2.rel = "stylesheet";
	style2.href = "http://www.duowan.com/assets/css/dwzq-common.css";
	style2.media = "all";
	document.getElementsByTagName("head")[0].appendChild(style2);
}			

/*
*	查询需要加载投票的div及初始化载入必要的文件 
*/			
DWCmsVote.cmsVoteInit = function(){
	
	this.loadCss();
	
	if(typeof(jQuery) == 'function' &&  typeof(jQuery(DWCmsVote.frameId).on) == 'function'){
		DWCmsVote.cmsVoteOnload();
		return ;
	}
	var doc = document,
		head = doc.getElementsByTagName("head")[0],
		js;
	js = doc.createElement('script');
	js.src = 'http://www.duowan.com/public/assets/sys/js/jquery-1.7.2.min.js?20121224.js';
	head.appendChild(js);
	if(typeof(js.onreadystatechange) != 'undefined'){
		js.onreadystatechange = function(){
			DWCmsVote.cmsVoteOnload();
		}
	}else{
		js.onload = function(){
			DWCmsVote.cmsVoteOnload();
		}
	}
	
} 

DWCmsVote.cmsVoteInit();